package com.xzz.sort;

import java.util.Arrays;

/**
 * @author: hhz
 * @create: 2021-12-31 09:31
 * 归并排序
 **/
public class MergeSort {

    public static void main(String[] args) {
        int[] arr = new int[]{4, 6, 8, 5, 9, 2, 3, 7};
//        int[] arr = new int[]{9, 7};
        int[] temp = new int[arr.length];
        mergeSort(arr, 0, arr.length - 1, temp);
        System.out.println(Arrays.toString(arr));
    }

    public static void mergeSort(int[] arr, int left, int right, int[] temp) {

        if (left < right) {
            int mid = left + (right - left) / 2;
            mergeSort(arr, left, mid, temp);
            mergeSort(arr, mid + 1, right, temp);
            merge(arr, left, mid, right, temp);
        }
    }

    public static void merge(int[] arr, int left, int mid, int right, int[] temp) {
        int i = left;
        int j = mid + 1;
        int k = 0;
        while (i<=mid && j<=right){
            if(arr[i]<=arr[j]){
                temp[k++] = arr[i++];
            }else {
                temp[k++] = arr[j++];
            }
        }
        while (i<=mid){
            temp[k++] = arr[i++];
        }
        while (j<=right){
            temp[k++] = arr[j++];
        }
        int t= 0;
        while(left <= right){
            arr[left++] = temp[t++];
        }
    }
}
